package ru.zombator.taskman.server.query.corba.manual;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import ru.zombator.taskman.core.query.IPacket;
import ru.zombator.taskman.server.query.corba.ICorbaServerPOA;
import ru.zombator.taskman.server.query.corba.RemoteException;
import ru.zombator.taskman.server.utils.Base64;

public class CorbaServerImpl extends ICorbaServerPOA {
	private final CorbaServer serv;

	public CorbaServerImpl(CorbaServer serv) {
		this.serv = serv;
	}
	
	@Override
	public String getResponse(String request) throws RemoteException {
		byte[] reqBytes = Base64.decode(request);

		ObjectInputStream ois = null;
		ObjectOutputStream oos = null;
		try {
			ois = new ObjectInputStream(
					new ByteArrayInputStream(reqBytes));
			IPacket requestPacket = (IPacket) ois.readObject();

			IPacket responsePacket = serv.getResponse(requestPacket);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(responsePacket);
			byte[] respBytes = baos.toByteArray();
			String respString = Base64.encode(respBytes);
			return respString;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				ois.close();
				oos.close();
			} catch (IOException ee) {
			}
		}
		return null;
	}
}
